<template>
  <div>
    <!--  :http-request="handleUpload"
     :show-file-list="tags"  
      :file-list="fileList"
    -->
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :limit="1"
      accept=".mp4"
      :show-file-list="false"
      drag
      :auto-upload="false"
      :http-request="handleUpload"
      @change="handleChange"
      :on-progress="onProgress"
    >
      <div
        class="box"
        style="
          text-align: center;
          width: 360px;
          height: 180px;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
        "
      >
        <div>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        </div>
        <div class="el-upload__text">
          将文件拖到此处，或<em style="color: var(--primary-color)"
            >点击上传</em
          >
        </div>
      </div>
      <template #tip>
        <div class="progress" v-if="fileList[0]?.name">
          <div style="text-align: center">
            {{ fileList[0]?.name }}
          </div>
          <div style="margin-left: 20px">
            <el-progress :percentage="stepNumber" />
          </div>
        </div>
      </template>
    </el-upload>
  </div>
  <!-- 开始上传按钮 -->
</template>
<script setup>
import { imageUpload } from '@/api/classRoom/index';
const emit = defineEmits(['eventVideo', 'progress', 'updateData']);
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import classRoom from '@/modules';
const { videoUploadApi } = classRoom;
const uploadRef = ref(null); // 用于访问上传组件的引用
import * as Qiniu from 'qiniu-js';
import { getQiniuUploadToken } from '@/api/upload.js';
const form = ref('');
const name = ref('');
const tags = ref(false);
const options = ref('');
let fileList = ref([]);
let stepNumber = ref(0);
const durationTime = ref('');
const fileToUpload = ref(null);
const videoCoverImg = ref('');

const handleUpload = async (option) => {
  options.value = option;
  name.value = option.file.name;
  tags.value = true;
  const { data } = await getQiniuUploadToken();
  const upToken = data[0].token;
  const config = {
    useCdnDomain: true,
    disableStatisticsReport: false,
    retryCount: 6,
    container: null,
    region: null,
  };

  // 指定上传路径，假设文件夹名是 "videos"
  const folderPath = 'videos/'; // 你的文件夹名称
  const fileName = `${folderPath}${option.file.name}`; // 确保文件名带有文件夹路径

  const observable = Qiniu.upload(option.file, fileName, upToken, null, config);
  return observable.subscribe({
    next(resp) {
      option.onProgress({ percent: resp.total.percent });
    },
    error(err) {
      option.onError(err);
    },
    complete(resp) {
      console.log('resp:', resp);
      // 上传成功后将文件名保存到form中 '/hy/loyGIcUWM5CCSR4-tLcBuOX22g_5'
      form.value = 'https://mcdn.chatgk.com/' + resp.key;
      videoUpload(form.value, name.value, durationTime.value);
      option.onSuccess(resp);
      // 清空文件列表
      fileList.value = [];
      stepNumber.value = 0; // 重置进度条
      fileToUpload.value = null; // 清空当前选择的文件
      if (uploadRef.value) {
        uploadRef.value.clearFiles(); // Clear the files in el-upload
      }
    },
  });
};
const thumbnail = ref('');

// 处理文件变化
const handleChange = (file, fileList_) => {
  fileList.value = fileList_;
  fileToUpload.value = file.file; // 存储选中的文件

  const videoUrl = URL.createObjectURL(file.raw); // 创建临时 URL
  const video = document.createElement('video');
  video.src = videoUrl;

  video.addEventListener('loadedmetadata', () => {
    durationTime.value = formatDuration(video.duration); // 获取视频时长（秒）
    URL.revokeObjectURL(videoUrl); // 释放临时 URL
  });

  // 浏览器端视频帧捕获示例
  // 视频元数据加载完成后
  video.onloadedmetadata = () => {
    // 跳转到视频的第一帧
    video.currentTime = 0;

    // 获取视频的第一帧
    video.onseeked = () => {
      // 创建 canvas 来绘制视频的第一帧
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      // 设置 canvas 尺寸为视频的宽高
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      // 绘制视频的第一帧到 canvas 上
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      thumbnail.value = base64ToBlobUrl(
        canvas.toDataURL('image/png'),
        'image/png',
        'thumbnail.png'
      );
      imageUpload({ type: 'jpg', image: thumbnail.value }).then((res) => {
        if (res.code == 20000) {
          videoCoverImg.value = res.data.url;
        }
      });
    };
  };
};
const base64ToBlobUrl = (base64, mime, filename) => {
  const byteString = atob(base64.split(',')[1]);
  const arrayBuffer = new ArrayBuffer(byteString.length);
  const uint8Array = new Uint8Array(arrayBuffer);

  for (let i = 0; i < byteString.length; i++) {
    uint8Array[i] = byteString.charCodeAt(i);
  }

  return new File([uint8Array], filename, { type: mime });
};

//文件上传时候的钩子函数
const onProgress = (event) => {
  stepNumber.value = Math.round(event.percent);
  emit('progress', { stepNumber: stepNumber.value, tags: tags.value });
};

// 手动触发上传
const triggerUpload = () => {
  const uploadInstance = uploadRef.value;
  uploadInstance.submit(); // 调用 el-upload 的 submit 方法进行上传
  fileList.value = [];
};
const videoUpload = async (url, name, durationTime) => {
  const res = await videoUploadApi({
    imgUrl: url,
    name: name,
    video_time: durationTime,
    cover: videoCoverImg.value,
  });
  if (res.code == 20000) {
    ElMessage({
      message: res.msg,
      type: 'success',
    });
    emit('updateData');
    emit('eventVideo', options.value, res.data, url, durationTime);
  }
};
// 删除文件
// 格式化时长为 "分钟:秒"
const formatDuration = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60)
    .toString()
    .padStart(2, '0');
  return `${mins}分钟${secs}秒`;
};

defineExpose({
  triggerUpload,
});
</script>
<style lang="scss" scope>
.progress {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-top: 10px;
}
</style>
